package com.lengtouzai.databaseexp.view.newfriend;


import com.lengtouzai.databaseexp.entity.User;
import com.lengtouzai.databaseexp.view.main.MainView;
import com.vaadin.flow.component.AbstractField;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.router.Route;
import io.jmix.core.security.CurrentAuthentication;
import io.jmix.flowui.Notifications;
import io.jmix.flowui.component.grid.DataGrid;
import io.jmix.flowui.component.textfield.TypedTextField;
import io.jmix.flowui.kit.component.button.JmixButton;
import io.jmix.flowui.model.CollectionLoader;
import io.jmix.flowui.view.*;
import org.springframework.beans.factory.annotation.Autowired;

@Route(value = "new-friend-view", layout = MainView.class)
@ViewController("exp_NewFriendView")
@ViewDescriptor("new-friend-view.xml")
public class NewFriendView extends StandardView {
    @ViewComponent
    private CollectionLoader<User> usersDl;
    @Autowired
    private CurrentAuthentication currentAuthentication;
    @ViewComponent
    private DataGrid<User> usersDataGrid;
    @Autowired
    private Notifications notifications;
    // selected user
    private User selected;

    public User getSelected() {
        return selected;
    }

    @Subscribe
    public void onReady(final ReadyEvent event) {
        User current = (User) currentAuthentication.getUser();
        usersDl.setParameter("user", current);
        usersDl.load();
    }

    @Subscribe(id = "addBtn", subject = "clickListener")
    public void onAddBtnClick(final ClickEvent<JmixButton> event) {
        User selected = usersDataGrid.getSingleSelectedItem();
        if (selected == null) {
            notifications.create("Please select a user").withType(Notifications.Type.ERROR).show();
            return;
        }
        this.selected = selected;
        close(StandardOutcome.SAVE);
    }

    @Subscribe("searchField")
    public void onSearchFieldComponentValueChange(final AbstractField.ComponentValueChangeEvent<TypedTextField<?>, ?> event) {
        usersDl.setParameter("username", "(?i)%" + event.getValue() + "%");
        usersDl.load();
    }

    @Subscribe(id = "cancelBtn", subject = "clickListener")
    public void onCancelBtnClick(final ClickEvent<JmixButton> event) {
        close(StandardOutcome.CLOSE);
    }
}